package com.rensea.android.api;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;

import android.util.Log;

import com.rensea.android.objs.LoginUser;
import com.rensea.android.util.Constants;

public abstract class AbstractAPIClient {

	public static final String Server = "http://renjian.com";
	public static final String MobileServer = "http://m.renjian.com";
	public static final String CookieDomain = "renjian.com";
	public static final String VERIFY_SERVICE = Server+"/account/verify_credentials.json";
	protected static class ResponseContent{
		boolean success = false;
		String result = "";
		private ResponseContent(boolean success, String result) {
			this.success = success;
			this.result = result;
		}
		
	}
	protected static String getContent(HttpResponse resp) throws IllegalStateException, IOException {
		if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			return getContent(resp.getEntity());
		}else{
			logD(resp.getStatusLine().getStatusCode()+"");
			logD(getContent(resp.getEntity()));
		}
		return null;
	}
	protected static ResponseContent getResponseContent(HttpResponse resp) throws IllegalStateException, IOException {
		if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			return new ResponseContent(true,getContent(resp.getEntity()));
		}else{
			return new ResponseContent(false,getContent(resp.getEntity()));
		}
	}
	private static String getContent(HttpEntity entity) throws IllegalStateException, IOException{
		InputStream is = entity.getContent();
		byte[] data = new byte[1024];
		int n;
		ByteArrayBuffer buf = new ByteArrayBuffer(1024);
		while ((n = is.read(data)) != -1)
			buf.append(data, 0, n);
		String str = new String(buf.toByteArray(), HTTP.UTF_8);
		return str;
		
	}
	protected static boolean isLogin(){
		return LoginUser.getLoginUser()!=null && LoginUser.getLoginUser().getCookie()!=null;
	}
	protected static HttpClient getHttpClientWithCookie(){
		DefaultHttpClient httpClient = new DefaultHttpClient(); 
		
		if(null!=LoginUser.getLoginUser() && null!=LoginUser.getLoginUser().getCookie()){
			httpClient.getCookieStore().addCookie(LoginUser.getLoginUser().getCookie());
		}
		return httpClient;
	}
	protected static void logD(String msg){
		Log.d(Constants.LOG_TAG,msg);
	}
	protected static void logD(String msg,Throwable ex){
		Log.d(Constants.LOG_TAG,msg,ex);
	}
}